import { listTree, save, remove, update } from '@/services/system/area';
import { treeDataWrapper } from '@/utils/common';
import { message } from 'antd';

const Model = {
  namespace: 'SystemAreaModel',
  state: {
    formVisible: false,
    formType: 'raise',
    treeData: [],
    selectData: null,
    area: {
      parentId: null,
      name: '',
      sort: 1,
      remark: ''
    },
  },
  effects: {
    *listTreeEffect(_, { call, put }) {
      const response = yield call(listTree);
      const listData = Array.isArray(response.data) ? response.data : [];

      yield put({ type: 'selectDataReducer', payload: listData.length > 0 ? listData[0] : null });

      treeDataWrapper(listData);
      yield put({ type: 'ListTreeReducer', payload: listData });
    },
    *saveEffect({ payload }, { call }) {
      const response = yield call(save, payload);

      if (response.success) message.success('新建区域成功!');
      else message.error('新建区域失败!');
    },
    *updateEffect({ payload }, { call }) {
      const response = yield call(update, payload);

      if (response.success) message.success('修改区域成功!');
      else message.error('修改区域失败!');
    },
    *removeEffect(_, { select, call }) {
      const { selectData } = yield select((state) => state.SystemAreaModel);
      const response = yield call(remove, selectData.id);

      if (response.success) message.success('删除区域成功!');
      else message.error('删除区域失败!');
    },
  },
  reducers: {
    ListTreeReducer(state, { payload }) {
      return { ...state, treeData: payload };
    },
    selectDataReducer(state, { payload }) {
      return { ...state, selectData: payload };
    },
    changeFormVisibleReducer(state, { payload }) {
      return { ...state, formVisible: payload };
    },
    formHandleReducer(state, { payload }) {
      if (payload === 'raise') {
        return { 
          ...state, 
          formVisible: true,  
          formType: payload, 
          area: {
            parentId: null,
            name: '',
            sort: 1,
            remark: ''
          }
        };
      }

      if (payload === 'modify') {
        return { ...state, formVisible: true,  formType: payload, area: state.selectData};
      }
    }
  }
};

export default Model;
